package com.rui.common.exception;

import com.rui.common.util.HttpStatus;
import com.rui.common.util.Res;
import lombok.extern.log4j.Log4j2;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 自定义异常handler
 *
 * @author xr
 * @email xr@qq.com
 * @date 2020-01-01 00:00:00
 */
@Log4j2
@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(MyException.class)
    public Res handleMyException(MyException e) {
        log.error(e.getMessage());
        return new Res().failure(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Res handleException(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return new Res().failure(HttpStatus.FAILURE);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Res handlerNoFoundException(Exception e) {
        log.error(e.getMessage());
        return new Res().failure(HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Res handleDuplicateKeyException(DuplicateKeyException e) {
        log.error(e.getMessage());
        return new Res().failure("数据库中已存在该记录");
    }

}
